//
//  QPJHPayView.m
//  QPJHLightSDK
//
//  Created by fish on 2022/1/7.
//  Copyright © 2022 Vanney. All rights reserved.
//

#import "QPJHPayView.h"
#import "QPConstHeader.h"
#import "QPJHFunDataFormat.h"
#import <WebKit/WebKit.h>
#import "QPSaccountStore.h"
#import "UIView+Toast.h"
#import "SQPJHNetworkManager.h"

@interface QPJHPayView ()<WKUIDelegate, WKNavigationDelegate,UITextViewDelegate>
@property (nonatomic, strong) UIButton *coverView;
@property (nonatomic, strong) UIButton *closeBtn;
@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UILabel *name;
@property (nonatomic, strong) UILabel *payMoney;

@property (nonatomic, strong) UILabel *payTipLabel;

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *payMoneyLabel;

@property (nonatomic, strong) UILabel *leftLabel;
@property (nonatomic, strong) UILabel *rightLabel;
@property (nonatomic, strong) UIImageView *leftImage;
@property (nonatomic, strong) UIImageView *rightImage;
@property (nonatomic, copy) NSString *order_id;
@property (strong, nonatomic) WKWebView *wkWebView;

@property (nonatomic, strong) UIView *line;

@end

@implementation QPJHPayView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self drawIt];
    }
    return self;
}
- (void)drawIt {
    [self addSubview:self.contentView];
    [self.contentView addSubview:self.closeBtn];
    [self.contentView addSubview:self.nameLabel];
    [self.contentView addSubview:self.payMoneyLabel];
    [self.contentView addSubview:self.name];
    [self.contentView addSubview:self.payMoney];

    [self.contentView addSubview:self.payTipLabel];
    [self.contentView addSubview:self.leftImage];
    [self.contentView addSubview:self.rightImage];
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.leftLabel];
    [self.contentView addSubview:self.rightLabel];
    [self.contentView addSubview:self.line];

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = [[WKUserContentController alloc] init];
    WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    self.wkWebView = wkWebView;
    if(@available(iOS 11.0, *)) {
        wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    wkWebView.UIDelegate = self;
    wkWebView.navigationDelegate = self;
    wkWebView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:wkWebView];
    self.wkWebView.frame = CGRectMake(0, 0, 0, 0);
    
    if (IS_LANDSCAPE) {
        self.contentView.frame =  UILanRectAdapter(0, 0, 320, 280);
        self.titleLabel.frame =  UILanRectAdapter(40, 8, 240, 30);

        self.closeBtn.frame = UILanRectAdapter(280, 0, 36, 36);
        self.nameLabel.frame = UILanRectAdapter(15, 60, 80, 30);
        self.payMoneyLabel.frame = UILanRectAdapter(15, 90, 80, 30);
        self.name.frame = UILanRectAdapter(95, 60, 208, 30);
        self.payMoney.frame = UILanRectAdapter(95, 90, 208, 30);
        
        self.payTipLabel.frame = UILanRectAdapter(15, 170, 120, 20);
        
        self.leftImage.frame = UILanRectAdapter(75, 205, 36, 36);
        self.rightImage.frame = UILanRectAdapter(195, 205, 36, 36);
        self.leftLabel.frame = UILanRectAdapter(77, 240, 60, 30);
        self.rightLabel.frame = UILanRectAdapter(192, 240, 60, 30);
        self.line.frame = UILanRectAdapter(12, 150, 296, 0.5);

    } else {
        self.contentView.frame =  UIPorRectAdapter(0, 0, 320, 280);
        self.titleLabel.frame =  UIPorRectAdapter(40, 8, 240, 30);

        self.closeBtn.frame = UIPorRectAdapter(280, 0, 36, 36);
        self.nameLabel.frame = UIPorRectAdapter(15, 60, 80, 30);
        self.payMoneyLabel.frame = UIPorRectAdapter(15, 90, 80, 30);
        self.name.frame = UIPorRectAdapter(95, 60, 208, 30);
        self.payMoney.frame = UIPorRectAdapter(95, 90, 208, 30);
        
        self.payTipLabel.frame = UIPorRectAdapter(15, 170, 120, 20);
        
        self.leftImage.frame = UIPorRectAdapter(75, 205, 36, 36);
        self.rightImage.frame = UIPorRectAdapter(195, 205, 36, 36);
        self.leftLabel.frame = UIPorRectAdapter(77, 240, 60, 30);
        self.rightLabel.frame = UIPorRectAdapter(192, 240, 60, 30);
        self.line.frame = UIPorRectAdapter(12, 150, 296, 0.5);

    }

    
    NSData *data = [NSData new];
    data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://qpyx-rlsb.oss-cn-shanghai.aliyuncs.com/2022/01/06/86179edab17542c393700a9e5f891f91.png"]];
    NSData *data1 = [NSData new];
    data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://qpyx-rlsb.oss-cn-shanghai.aliyuncs.com/2022/01/06/8b2ee76e89a847edb5d61dbb94d69c4f.png"]];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.leftImage.image = [UIImage imageWithData:data];
        self.rightImage.image = [UIImage imageWithData:data1];
    });
    
    UITapGestureRecognizer *leftTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLeftImg)];
    leftTap.numberOfTapsRequired = 1;
    leftTap.numberOfTouchesRequired = 1;
    [self.leftImage addGestureRecognizer:leftTap];
    
    UITapGestureRecognizer *rightTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRightImg)];
    rightTap.numberOfTapsRequired = 1;
    rightTap.numberOfTouchesRequired = 1;
    [self.rightImage addGestureRecognizer:rightTap];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillEnterForeground)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
}
- (void)tapLeftImg {
    if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"weixin://"]] == YES || [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"Whatapp://"]] == YES) {
        NSString *chrandom = [QPJHFunDataFormat QPJHMD5GetRandomStr];
        NSString *chmd5str = [NSString stringWithFormat:@"%@%@%@%@",self.order_id,@"2",chrandom,@"892984b23632e3c09b83f37025951013"];
        NSString *chsign = [QPJHFunDataFormat QPJHMD5WithNSString:chmd5str];
        
        NSString *url = [NSString stringWithFormat:@"https://supersdk.7pa.com/pay/index?order_id=%@&pay_type=%@&random=%@&sign=%@",self.order_id,@"2",chrandom,chsign];

        NSString *urlString = [[url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] stringByReplacingOccurrencesOfString:@" " withString:@""];
        urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *webURL = [NSURL URLWithString:urlString];

        NSMutableURLRequest *webRequst = [NSMutableURLRequest requestWithURL:webURL];
        [webRequst setHTTPMethod:@"GET"];
        [self.wkWebView loadRequest:webRequst];
        
    } else {
        [[[QPSaccountStore sharedInstance] getCurrentWindow] makeToast:@"您暂未安装微信"];
    }
}
- (void)tapRightImg {
    NSString *chrandom = [QPJHFunDataFormat QPJHMD5GetRandomStr];
    NSString *chmd5str = [NSString stringWithFormat:@"%@%@%@%@",self.order_id,@"1",chrandom,@"892984b23632e3c09b83f37025951013"];
    NSString *chsign = [QPJHFunDataFormat QPJHMD5WithNSString:chmd5str];

    
    NSString *url = [NSString stringWithFormat:@"https://supersdk.7pa.com/pay/index?order_id=%@&pay_type=%@&random=%@&sign=%@",self.order_id,@"1",chrandom,chsign];
    
    NSString *urlString = [[url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] stringByReplacingOccurrencesOfString:@" " withString:@""];
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *webURL = [NSURL URLWithString:urlString];
    
    NSURL * myURL_APP_A = [NSURL URLWithString:@"alipay:"];
    if ([[UIApplication sharedApplication] canOpenURL:myURL_APP_A]) {
       
        NSMutableURLRequest *webRequst = [NSMutableURLRequest requestWithURL:webURL];
        [webRequst setHTTPMethod:@"GET"];
        self.wkWebView.frame = CGRectMake(0, 0, 1, 1);
        [self.wkWebView loadRequest:webRequst];
        
    } else {
        [[UIApplication sharedApplication] openURL:webURL];
    }

}
- (void)applicationWillEnterForeground {
    //NSLog(@"applicationWillEnterForeground");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            
            UIViewController *vc = [[UIViewController alloc] init];
            [[UIApplication sharedApplication].keyWindow addSubview:vc.view];
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@""
                                                                                     message:@"您是否成功支付?"
                                                                              preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"已支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //NSLog(@"已支付");
                [self checkOrderWithOrderID:self.order_id];
                
                [vc.view removeFromSuperview];
                
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"未支付" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"未支付");
               // [self checkOrderWithOrderID:self.order_id];
                [vc.view removeFromSuperview];
            }];
            
            [alertController addAction:okAction];
            [alertController addAction:cancelAction];
            [vc presentViewController:alertController animated:YES completion:nil];
        });
    });
}
- (void)checkOrderWithOrderID:(NSString *)orderid {

    NSString *url = [NSString stringWithFormat:@"https://supersdk.7pa.com/checkorder/index?order_id=%@",orderid];    
    [SQPJHNetworkManager getWithURL:url Params:nil success:^(id responseObject) {
        NSDictionary *surperdic = (NSDictionary *)responseObject;
        NSString *status = [NSString stringWithFormat:@"%@",surperdic[@"code"]];
        
        [self dissmiss];
        if ([status isEqualToString:@"200"]) {
            
            if (self.payBlock) {
                self.payBlock(@"1");
            }
        } else {
            if (self.payBlock) {
                self.payBlock(@"0");
            }
        }
    } failure:^(NSString *error) {
        if (self.payBlock) {
            self.payBlock(@"0");
        }
    }];
}
// 编码
- (NSString *)URLEncodedString:(NSString *)str{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)str,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}
// 解码
- (NSString *)URLDecodedString:(NSString *)str{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSURLRequest *request = navigationAction.request;
        NSString *absoluteString = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
        
    if ([absoluteString hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![absoluteString hasSuffix:[NSString stringWithFormat:@"redirect_url=supersdk.7pa.com"]]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        NSString *redirectUrl = nil;
        if ([absoluteString containsString:@"redirect_url="]) {
            NSRange redirectRange = [absoluteString rangeOfString:@"redirect_url"];
            redirectUrl = [[absoluteString substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"redirect_url=supersdk.7pa.com"]];
        } else {
            redirectUrl = [absoluteString stringByAppendingString:[NSString stringWithFormat:@"redirect_url=supersdk.7pa.com"]];
        }
        NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields;
        newRequest.URL = [NSURL URLWithString:redirectUrl];
        [newRequest setValue:@"https://supersdk.7pa.com" forHTTPHeaderField:@"Referer"];
        [webView loadRequest:newRequest];
        return;
    }
        
    if ([absoluteString hasPrefix:@"weixin://"]) {
        decisionHandler(WKNavigationActionPolicyAllow);
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        return;
    }
    
    if ([navigationAction.request.URL.absoluteString containsString:@"alipay://"]||[navigationAction.request.URL.absoluteString containsString:@"alipays://"]){// 支付宝
        decisionHandler(WKNavigationActionPolicyCancel);
        NSString *decodedString = [self URLDecodedString:navigationAction.request.URL.absoluteString];
        if ([decodedString containsString:@"fromAppUrlScheme"]) {
            NSString *subStr = [decodedString stringByReplacingOccurrencesOfString:@"alipay://alipayclient/?" withString:@""];

            NSString *repStr = [subStr stringByReplacingOccurrencesOfString:@"alipays" withString:@"supersdk.7pa.com"];
            NSString *encodedString = [NSString stringWithFormat:@"alipay://alipayclient/?%@",[self URLEncodedString:repStr]];

            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:encodedString]];
            return;
        } else {
            [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
            return;
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    return;
}

- (void)binGoodname:(NSString *)goodname Money:(NSString *)money Orderid:(NSString *)orderid {
    self.order_id = orderid;
    self.name.text = goodname;
    self.payMoney.text = [NSString stringWithFormat:@"%@元",money];

}

- (void)show {
    UIButton *coverView = [[UIButton alloc] init];
    coverView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3f];
    self.coverView = coverView;

    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    coverView.frame = window.bounds;
    
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    visualView.alpha = 0.5;
    [coverView addSubview:visualView];
    visualView.frame = coverView.frame;
    [window addSubview:coverView];
    self.frame = IS_LANDSCAPE ? UILanRectAdapter(0, 0, 320, 280): UIPorRectAdapter(0, 0, 320, 280);
    self.center = window.center;
    [window addSubview:self];
}
- (void)dissmiss {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.coverView removeFromSuperview];
        [self.closeBtn removeFromSuperview];
        [self removeFromSuperview];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        
    });
}

- (UIView *)contentView {
    if (_contentView == nil) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.userInteractionEnabled = YES;
        _contentView.layer.cornerRadius = 10;
    }
    return _contentView;
}
- (UIButton *)closeBtn {
    if (_closeBtn == nil) {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn addTarget:self action:@selector(dissmiss) forControlEvents:UIControlEventTouchUpInside];
        [_closeBtn setTitle:@"x" forState:UIControlStateNormal];
        _closeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:25];
        [_closeBtn setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    }
    return _closeBtn;
}
- (UILabel *)titleLabel {
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont boldSystemFontOfSize:18];
        _titleLabel.text = @"充值中心";
    }
    return _titleLabel;
}
- (UILabel *)nameLabel {
    if (_nameLabel == nil) {
        _nameLabel = [[UILabel alloc] init];
        _nameLabel.text = @"购买道具:";
        _nameLabel.font = [UIFont boldSystemFontOfSize:17];
        _nameLabel.textAlignment = NSTextAlignmentLeft;
    }
    return _nameLabel;
}
- (UILabel *)payMoneyLabel {
    if (_payMoneyLabel == nil) {
        _payMoneyLabel = [[UILabel alloc] init];
        _payMoneyLabel.text = @"应付金额:";
        _payMoneyLabel.font = [UIFont boldSystemFontOfSize:17];
        _payMoneyLabel.textAlignment = NSTextAlignmentLeft;
    }
    return _payMoneyLabel;
}
- (UILabel *)leftLabel {
    if (_leftLabel == nil) {
        _leftLabel = [[UILabel alloc] init];
        _leftLabel.text = @"微信";
        _leftLabel.font = [UIFont systemFontOfSize:15];
        _leftLabel.textAlignment = NSTextAlignmentLeft;

    }
    return  _leftLabel;;
}
- (UILabel *)rightLabel {
    if (_rightLabel == nil) {
        _rightLabel = [[UILabel alloc] init];
        _rightLabel.text = @"支付宝";
        _rightLabel.font = [UIFont systemFontOfSize:15];
        _rightLabel.textAlignment = NSTextAlignmentLeft;

    }
    return  _rightLabel;;
}
- (UILabel *)name {
    if (_name == nil) {
        _name = [[UILabel alloc] init];
        _name.font = [UIFont boldSystemFontOfSize:17];
        _name.textAlignment = NSTextAlignmentRight;
    }
    return  _name;
}
- (UILabel *)payMoney {
    if (_payMoney == nil) {
        _payMoney = [[UILabel alloc] init];
        _payMoney.font = [UIFont boldSystemFontOfSize:18];
        _payMoney.textColor = UIColor.redColor;
        _payMoney.textAlignment = NSTextAlignmentRight;

    }
    return  _payMoney;
}
- (UILabel *)payTipLabel {
    if (_payTipLabel == nil) {
        _payTipLabel = [[UILabel alloc] init];
        _payTipLabel.text = @"支付方式:";
        _payTipLabel.font = [UIFont boldSystemFontOfSize:17];
        _payTipLabel.textAlignment = NSTextAlignmentLeft;

    }
    return  _payTipLabel;
}

- (UIImageView *)leftImage {
    if (_leftImage == nil) {
        _leftImage = [UIImageView new];
        _leftImage.userInteractionEnabled = YES;
    }
    return _leftImage;
}
-(UIImageView *)rightImage {
    if (_rightImage == nil) {
        _rightImage = [UIImageView new];
        _rightImage.userInteractionEnabled = YES;
    }
    return _rightImage;
}
- (UIView *)line {
    if (_line == nil) {
        _line = [[UIView alloc] init];
        _line.backgroundColor = UIColor.lightGrayColor;
    }
    return _line;
}
@end
